const Product = require('../modules/product');

exports.getProductList = (req, res, next) => {
    Product.find({ userId: req.user._id })
    .then(products => {
        res.render('admin/product-list', {
            prods: products,
            path: '/admin/product-list',
            pageTitle: '管理产品'
        })
    })
    .catch(err => console.log(err))
}
exports.getEditProduct = (req, res, next) => {
    const prodId = req.params.prodId;
    Product.findById(prodId)
    .then(product => {
        res.render('admin/edit-product', {
            product: product || {},
            pageTitle: '添加产品', 
            path: '/admin/add-product'
        });
    })
    .catch(err => console.log(err))
}

exports.postEditProduct = (req, res, next) => {
    const { id, title, imageUrl, price, description } = req.body;
    if(id) {
        Product.updateOne(
        {
            _id: id
        }, 
        {
            title, 
            imageUrl, 
            price, 
            description
        })
        .then(result => {
            res.redirect('/admin/product-list');
        })
        .catch(err => console.log(err))
    } else {
        Product.create({
            title, 
            imageUrl, 
            price, 
            description,
            userId: req.user._id
        })
        .then(result => {
            res.redirect('/admin/product-list');
        })
        .catch(err => console.log(err))
    }
}

exports.postDeleteProduct = (req, res, next) => {
    const prodId = req.body.prodId;
    Product.deleteOne({ _id: prodId })
    .then(result => {
        res.redirect('/admin/product-list');
    })
    .catch(err => console.log(err))
}